/**
 *
 */

import { isArray } from 'fc-cli-core'
import FCRule from './FCRule'

class FCRuleTableRecord {
  /* properties */

  key
  table
  rules = []

  // 默认规则，用于获取当前 record 共性，例如 colFactorKey
  defaultRule

  // 显示在 单元格结果 cell-result 中的规则，以 dataIndex 为 key
  cellResultRuleMap = {}

  // 显示在 列结果 col-result 中的规则，每个 record 最多只有一个
  colResultRule

  /* lifecycle methods */

  constructor({ key, table } = {}) {
    this.key = key
    this.table = table
  }

  /* public methods */

  addRuleData(ruleData) {
    const rule = new FCRule({
      key: this.createNewRuleKey(),
      factors: this.table.factors,
      data: ruleData,
    })

    if (!this.defaultRule) {
      this.defaultRule = rule
    }

    this.addRule(rule)
  }

  addRule(rule) {
    if (this.isCellResultRule(rule)) {
      this.addCellResultRule(rule)
    } else if (this.isColResultRule(rule)) {
      this.setColResultRule(rule)
    } else {
      console.log(`[addRule]: error, rule is neither cellResult nor colResult`)
    }
  }

  addCellResultRule(rule) {
    //
    //
    const dataIndex = this.getDataIndexWithCellResultRule(rule)
    if (this.cellResultRuleMap[dataIndex]) {
      console.log(`[addCellResultRule] error: dataIndex ${dataIndex} has already exist: ${this.cellResultRuleMap[dataIndex]}`)
    }
    this.cellResultRuleMap[dataIndex] = rule
  }

  setColResultRule(rule) {
    if (this.colResultRule) {
      console.log(`[setColResultRule] error: this.colResultRule has already exist: ${this.colResultRule}`)
    }
    this.colResultRule = rule
  }

  // 获取 cell result rule 的 dataIndex
  getDataIndexWithCellResultRule(rule) {
    const valuePath = this.table.rowConditions.map((factor) => ({ code: factor.code, value: rule.getValue(factor.code) }))
    const dataIndex = dataIndexWithValuePath(valuePath)
    return dataIndex
  }

  // 获取 data 的 dataIndex
  getDataIndexWithRuleData(ruleData) {
    // const rule = new FCRule({
    //   key: this.createNewRuleKey(),
    //   factors: this.table.factors,
    //   data: ruleData,
    // })
    // if (this.isCellResultRule(rule)) {
    //   this.addCellResultRule(rule)
    // } else if (this.isColResultRule(rule)) {
    //   this.setColResultRule(rule)
    // }
    // return '1-2-3'
    // const valuePath = this.getValuePathWithRuleData(ruleData)
    // return dataIndexBuilder(valuePath)
  }

  // 获取 data 的 valuePath
  getValuePathWithRuleData(ruleData) {
    // this.rowCon
    const valuePath = []

    return valuePath
  }

  getColFactorKeyWithRuleData(ruleData) {
    return '-'
  }

  getRuleDatas() {
    const ruleDatas = []
    Object.values(this.cellResultRuleMap).forEach((rule) => {
      ruleDatas.push(rule.getValues())
    })

    if (this.colResultRule) {
      ruleDatas.push(this.colResultRule.getValues())
    }

    return ruleDatas
  }

  // addRule(rule) {
  //   // 如果当前 rule 是 col-result rule
  //   if (this.isColResultRule(rule)) {
  //     this.#colResultRule = rule
  //   }

  //   // 如果当前 rule 是 cell-result rule
  //   if (this.isCellResultRule(rule)) {
  //     const dataIndex = this.getDataIndexWithRule(rule)

  //     // todo: 判断 dataIndex 是否有重复
  //     this.#resultRulesByDataIndex[dataIndex] = rule
  //   }

  //   //
  //   this.rules.push(rule)
  // }

  buildTableDataSource() {
    const keyValues = { key: this.key }

    const colFactorValues = this.buildColFactorValues()
    const cellResultValues = this.buildCellResultValues()
    const colResultValues = this.buildColResultValues()

    return { ...keyValues, ...colFactorValues, ...cellResultValues, ...colResultValues }
  }

  // 获取 colFactor 对应的 dataSource
  buildColFactorValues() {
    if (!this.defaultRule) {
      return {}
    }

    const values = {}

    this.table.colConditions.forEach((factor) => {
      const { code: dataIndex } = factor
      values[dataIndex] = this.defaultRule.getLabel(dataIndex)
    })

    return values
  }

  // 获取 cellResult 对应的 dataSource
  buildCellResultValues() {
    if (!this.table.rowConditions) {
      return {}
    }

    if (!this.table.defaultCellResultFactor) {
      return {}
    }

    const values = {}
    const cellResultCode = this.table.defaultCellResultFactor.code

    Object.keys(this.cellResultRuleMap).forEach((dataIndex) => {
      const rule = this.cellResultRuleMap[dataIndex]
      values[dataIndex] = rule.getLabel(cellResultCode)
    })

    return values
  }

  // 获取 colResult 对应的 dataSource
  buildColResultValues() {
    if (!this.colResultRule) {
      return {}
    }

    const values = {}
    this.table.colResults.forEach((factor) => {
      const { code: dataIndex } = factor
      values[dataIndex] = this.colResultRule.getLabel(dataIndex)
    })

    return values
  }

  // 为当前 column.dataIndex 对应的 colCondition/colResult/cellResult 设置 value
  setCellValue({ value, dataIndex }) {
    let { rules, factor } = this.getCellInfoWithDataIndex(dataIndex)
    if (!rules[0]) {
      this.fillUpRules(dataIndex)
      rules = this.getRulesWithDataIndex(dataIndex)
    }
    rules.forEach((rule) => {
      rule.setValue({ code: factor.code, value })
    })
  }

  getCellValue(dataIndex) {
    // const { rules, factor } = this.getCellInfoWithDataIndex(dataIndex)
    // if (!isArray(rules) || rules.length <= 0 || !rules[0]) {
    //   return undefined
    // }
    // return rules[0].getValue(factor.code)
  }

  getCellText(dataIndex) {
    // const { rules, factor } = this.getCellInfoWithDataIndex(dataIndex)
    // if (!isArray(rules) || rules.length <= 0 || !rules[0]) {
    //   return '--'
    // }
    // return rules[0].getLabel(factor.code)
  }

  // 获取当前 dataIndex 对应的 cellFactor 和 rule
  getCellInfoWithDataIndex(dataIndex) {
    // const rules = this.getRulesWithDataIndex(dataIndex)
    // const factor = this.getCellFactorWithDataIndex(dataIndex)
    // return { rules, factor }
  }

  // 获取当前 cell 的 highlight 信息
  getCellStyle(dataIndex) {
    const rules = this.getRulesWithDataIndex(dataIndex)
    const factor = this.getCellFactorWithDataIndex(dataIndex)

    let styles = {}

    for (let i = 0; i < rules.length; i++) {
      const rule = rules[i]
      const style = rule?.getStyle(factor.code)
      if (!style) {
        continue
      }
      styles = { ...styles, ...style }
    }

    // console.log('>>> styles is:', styles)
    return styles
  }

  // 填充缺失的 rules
  // fillUpRules() {
  //   // cell result rules
  //   const cellResultRules = this.rules.filter((rule) => this.isCellResultRule(rule))
  //   const existedDataIndexList = cellResultRules.map((rule) => this.getDataIndexWithRule(rule))
  //   const missingDataIndexList = Object.keys(this.rowConditionDataIndexData).filter((dataIndex) => !existedDataIndexList.includes(dataIndex))
  //   missingDataIndexList.forEach((dataIndex) => {
  //     const ruleData = { ...this.defaultColConditionData }
  //     const rowConditionValues = this.rowConditionDataIndexData[dataIndex].values
  //     this.rowConditions.forEach((factor, factorIndex) => {
  //       ruleData[factor.code] = rowConditionValues[factorIndex]
  //     })
  //     ruleData[this.defaultCellResult.code] = undefined
  //     this.addRuleWithData(ruleData)
  //   })

  //   // col result rules
  //   const colResultRules = this.rules.filter((rule) => this.isColResultRule(rule))
  //   if (colResultRules.length === 0) {
  //     const ruleData = { ...this.defaultColConditionData }
  //     this.colResultCodes.forEach((code) => {
  //       ruleData[code] = undefined
  //     })
  //     this.addRuleWithData(ruleData)
  //   }
  // }

  // addRuleWithData(data) {
  //   const rule = new FCRule({
  //     key: this.createNewRuleKey(),
  //     factors: this.factors,
  //     data: data,
  //   })
  //   this.addRule(rule)
  // }

  /* private methods */

  // 总是返回数组
  getRulesWithDataIndex(dataIndex) {
    // // 如果是 colCondition
    // if (this.isColConditionDataIndex(dataIndex)) {
    //   return this.rules
    // }
    // // 如果是 colResult
    // if (this.isColResultDataIndex(dataIndex)) {
    //   return [this.#colResultRule]
    // }
    // // 如果是 cellResult
    // const cellResultRule = this.#resultRulesByDataIndex[dataIndex]
    // return [cellResultRule]
  }

  // dataIndex 是否为 col-condition.code
  isColConditionDataIndex(dataIndex) {
    // const findFactorIndex = this.colConditions.findIndex((factor) => factor.code === dataIndex)
    // return findFactorIndex >= 0
  }

  // dataIndex 是否为 col-result.code
  isColResultDataIndex(dataIndex) {
    // const findFactorIndex = this.colResults.findIndex((factor) => factor.code === dataIndex)
    // return findFactorIndex >= 0
  }

  // rule 是否为 col-result rule ，是否包含 col-result factor 的 code
  isColResultRule(rule) {
    return !rule.hasFactor(this.table.rowFactorCodes, 'every') && rule.hasFactor(this.table.colResultCodes)
  }

  // rule 是否为 cell-result rule，是否包含 row factor 的 code
  isCellResultRule(rule) {
    return rule.hasFactor(this.table.rowFactorCodes, 'every')
  }

  // 通过 column.dataIndex 获取 factor
  getCellFactorWithDataIndex(dataIndex) {
    // return this.#cellFactorsByDataIndex[dataIndex]
    //
  }

  getDataIndexWithRule(rule) {
    // const valuePath = this.getRowConditionFactorValuePath(rule)
    // return dataIndexBuilder(valuePath)
  }

  getRowConditionFactorValuePath(rule) {
    // return this.rowConditions.map((factor) => rule.getValue(factor.code))
  }

  // 生成 rule.key
  #ruleIndex = 1
  createNewRuleKey() {
    return `${this.key}-rule:${this.#ruleIndex++}`
  }
}

export default FCRuleTableRecord

const dataIndexBuilder = (valuePath) => {
  return valuePath.join('-')
}

const dataIndexWithValuePath = (valuePath) => {
  const values = valuePath.map((item) => item.value)
  return values.join('-')
}

export { dataIndexBuilder, dataIndexWithValuePath }
